<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #ffd700;
            --primary-light: #fff7cc;
            --primary-dark: #ffcd00;
            --danger-color: #ff4d4f;
            --success-color: #52c41a;
        }

        body {
            background-color: #fffdf5;
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .back-btn {
            background: transparent;
            border: none;
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
            font-size: 14px;
            padding: 8px 12px;
            margin-right: 20px;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: #f5f5f5;
            color: var(--primary-color);
        }

        .back-btn i {
            margin-right: 5px;
        }

        .order-tabs {
            display: flex;
            margin-bottom: 20px;
            background: white;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            position: relative;
            transition: all 0.3s;
            border-radius: 4px;
        }

        .tab:hover {
            background-color: var(--primary-light);
        }

        .tab.active {
            color: var(--primary-dark);
            background-color: var(--primary-light);
            font-weight: bold;
        }

        .order-item {
            border: 1px solid #eee;
            margin-bottom: 20px;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.3s;
            cursor: pointer;
        }

        .order-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            padding: 15px;
            border-bottom: 1px solid #eee;
            background-color: #fafafa;
            border-radius: 8px 8px 0 0;
        }

        .order-content {
            display: flex;
            padding: 20px;
            gap: 20px;
        }

        .product-image {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
        }

        .product-info {
            flex: 1;
        }

        .product-name {
            font-size: 16px;
            margin-bottom: 10px;
            color: #333;
        }

        .product-price {
            color: var(--danger-color);
            font-size: 18px;
            font-weight: bold;
        }

        .order-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-top: 1px solid #eee;
            background-color: #fafafa;
            border-radius: 0 0 8px 8px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            padding: 8px 16px;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .action-btn.primary {
            background: var(--primary-color);
            color: white;
        }

        .action-btn.danger {
            border-color: var(--danger-color);
            color: var(--danger-color);
        }

        .action-btn:hover {
            opacity: 0.8;
            transform: translateY(-1px);
        }

        .status-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            margin-left: 10px;
        }

        .status-pending {
            background-color: #fff7e6;
            color: #fa8c16;
        }

        .status-shipping {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-completed {
            background-color: #f6ffed;
            color: var(--success-color);
        }

        .status-cancelled {
            background-color: #fff1f0;
            color: var(--danger-color);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            position: relative;
            width: 500px;
            margin: 100px auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .modal-close {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 20px;
            color: #999;
            cursor: pointer;
            transition: all 0.3s;
        }

        .modal-close:hover {
            color: #666;
        }

        .order-detail-section {
            margin: 15px 0;
            padding: 15px;
            background: #fafafa;
            border-radius: 4px;
        }

        .order-detail-section h3 {
            margin: 0 0 10px 0;
            color: #333;
        }

        .detail-row {
            display: flex;
            margin: 8px 0;
        }

        .detail-label {
            width: 100px;
            color: #666;
        }

        .detail-value {
            flex: 1;
            color: #333;
        }

        .address-form {
            margin-top: 15px;
        }

        .address-form input {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 20px;
            color: #ddd;
        }

        .star-rating {
            color: #ffd700;
            font-size: 18px;
            margin: 10px 0;
        }
        
        .comment-time {
            color: #999;
            font-size: 14px;
            margin-top: 10px;
        }
        
        .comment-content {
            margin: 15px 0;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
            line-height: 1.6;
        }

        .address-list {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .address-item {
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .address-item:hover {
            background-color: var(--primary-light);
            border-color: var(--primary-color);
        }
        
        .address-item.selected {
            background-color: var(--primary-light);
            border-color: var(--primary-color);
        }
        
        .address-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .address-phone {
            color: #666;
            margin-bottom: 5px;
        }
        
        .address-detail {
            color: #333;
            line-height: 1.4;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 20px;
            border-radius: 8px;
            width: 60%;
            max-width: 600px;
            position: relative;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .close {
            font-size: 24px;
            cursor: pointer;
        }

        .star-rating {
            display: inline-block;
            font-size: 24px;
        }

        .star {
            color: #ddd;
            cursor: pointer;
        }

        .star.active {
            color: #f0ad4e;
        }

        .rating-container {
            margin-bottom: 20px;
        }

        .comment-input {
            margin-bottom: 20px;
        }

        .comment-input textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }

        .image-preview img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
        }

        .logistics-timeline {
            margin-top: 20px;
            padding: 20px;
        }

        .logistics-item {
            padding: 10px 0;
            border-left: 2px solid #e8e8e8;
            position: relative;
            padding-left: 20px;
            margin-bottom: 10px;
        }

        .logistics-item::before {
            content: '';
            width: 10px;
            height: 10px;
            background: #fff;
            border: 2px solid #1890ff;
            border-radius: 50%;
            position: absolute;
            left: -6px;
            top: 15px;
        }

        .logistics-item.active::before {
            background: #1890ff;
        }

        .logistics-time {
            color: #999;
            font-size: 12px;
        }

        .logistics-info {
            color: #333;
            margin-top: 5px;
        }

        .modal-body textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 100px;
            margin: 10px 0;
            font-size: 14px;
        }

        .modal-body textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
        }

        .modal-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
            margin-bottom: 15px;
        }

        .modal-footer {
            border-top: 1px solid #eee;
            padding-top: 15px;
            margin-top: 15px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .modal-body {
            padding: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <button class="back-btn" onclick="goBack()">
                <i class="fas fa-arrow-left"></i>返回
            </button>
        </div>
        <div class="order-tabs">
            <button class="tab active" onclick="filterOrders('all')">全部订单</button>
            <button class="tab" onclick="filterOrders('待付款')">待付款</button>
            <button class="tab" onclick="filterOrders('待发货')">待发货</button>
            <button class="tab" onclick="filterOrders('待收货')">待收货</button>
            <button class="tab" onclick="filterOrders('待评价')">待评价</button>
            <button class="tab" onclick="filterOrders('已评价')">已评价</button>
            <button class="tab" onclick="filterOrders('已取消')">已取消</button>
        </div>

        <div id="orderList">
            <!-- 订单列表将通过JavaScript动态加载 -->
        </div>
    </div>

    <!-- 订单详情模态框 -->
    <div id="orderDetailModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('orderDetailModal')">&times;</span>
            <h2>订��详情</h2>
            <div id="orderDetailContent"></div>
        </div>
    </div>

    <!-- 评价模态框 -->
    <div id="commentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>评价商品</h2>
                <span class="close" onclick="closeCommentModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="rating-container">
                    <div class="rating-label">商品评分：</div>
                    <div class="star-rating">
                        <span class="star" data-rating="1">★</span>
                        <span class="star" data-rating="2">★</span>
                        <span class="star" data-rating="3">★</span>
                        <span class="star" data-rating="4">★</span>
                        <span class="star" data-rating="5">★</span>
                    </div>
                </div>
                <div class="comment-input">
                    <textarea id="commentContent" placeholder="请输入您的评价内容..." rows="4"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeCommentModal()">取消</button>
                <button class="action-btn primary" onclick="submitComment()">提交评价</button>
            </div>
        </div>
    </div>

    <!-- 物流查看模态框 -->
    <div id="logisticsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>物流信息</h2>
                <span class="close" onclick="closeLogisticsModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div id="logisticsInfo">
                    <div class="logistics-header">
                        <div>快递公司：<span id="expressCompany"></span></div>
                        <div>快递单号：<span id="expressNumber"></span></div>
                    </div>
                    <div id="logisticsTimeline" class="logistics-timeline">
                        <!-- 物流信息将通过 JavaScript 动态添加 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 地址选择模态框 -->
    <div id="addressModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>选择收货地址</h2>
                <span class="close" onclick="closeModal('addressModal')">&times;</span>
            </div>
            <div class="address-list">
                <!-- 地址列表将���过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 取消订单确认模态框 -->
    <div id="cancelOrderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>取消订单</h2>
                <span class="close" onclick="closeModal('cancelOrderModal')">&times;</span>
            </div>
            <div class="modal-body">
                <textarea id="cancelReason" placeholder="请输入取消原因..." rows="4"></textarea>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeModal('cancelOrderModal')">取消</button>
                <button class="action-btn danger" onclick="confirmCancelOrder()">确认取消</button>
            </div>
        </div>
    </div>

    <script>
        let currentOrderId = null;
        
        // 页面加载完成后执行
        $(document).ready(function() {
            // 从URL获取状态参数
            const urlParams = new URLSearchParams(window.location.search);
            const status = urlParams.get('status') || 'all';
            
            // 设置对应的标签为激活状态
            $('.tab').removeClass('active');
            $(`.tab:contains('${status}')`).addClass('active');
            
            // 加载对应状态的订单
            loadOrders(status);
        });

        // 加载订单列表
        function loadOrders(status = 'all') {
            let url = '/buyer/order/list';
            let apiStatus = status;
            
            // 如果是待评价或已评价状态，使用新的接口
            if (status === '待评价' || status === '已评价') {
                url = '/buyer/order/listComment';
                apiStatus = status; // 递具体的状态给新接口
            }
            
            $.ajax({
                url: url,
                type: 'GET',
                data: { status: apiStatus },
                success: function(response) {
                    console.log("订单列表", response);
                    if (response.state === 1) {
                        renderOrders(response.data);
                    } else {
                        showEmptyState('加载订单失败');
                    }
                },
                error: function() {
                    showEmptyState('加载订单失败');
                }
            });
        }

        // 渲染订单列表
        function renderOrders(orders) {
            const orderList = $('#orderList');
            orderList.empty();

            if (!orders || orders.length === 0) {
                showEmptyState('暂无订单');
                return;
            }

            orders.forEach(order => {
                // 如果是评价相关的状态，使用buyerCommentStatus
                let displayStatus = order.status;
                if (order.buyerCommentStatus) {
                    displayStatus = order.buyerCommentStatus;
                }
                
                const statusClass = getStatusClass(displayStatus);
                const statusText = getStatusText(displayStatus);
                
                const orderHtml = `
                    <div class="order-item" onclick="viewOrderDetail('${order.orderNo}')">
                        <div class="order-header">
                            <div>
                                <span>订单号：${order.orderNo}</span>
                                <span class="status-tag ${statusClass}">${statusText}</span>
                            </div>
                            <div>
                                <span>卖家：${order.sellerNickname || '未知卖家'}</span>
                                <button class="action-btn" onclick="event.stopPropagation(); startChat('${order.sellerId}', '${order.productId}')">
                                    联系卖家
                                </button>
                                <span style="margin-left: 20px;">下单时间：${new Date(order.createTime).toLocaleString()}</span>
                            </div>
                        </div>
                        <div class="order-content">
                            <img src="${order.firstImage}" class="product-image" 
                                 alt="${order.productName}"
                                 onerror="this.src='images/default-product.png'">
                            <div class="product-info">
                                <div class="product-name">${order.productName}</div>
                                <div class="product-price">¥${order.price.toFixed(2)}</div>
                                ${order.buyerCommentStatus === '已评价' ? `
                                    <div class="comment-info">
                                        <button class="action-btn" onclick="event.stopPropagation(); viewComment('${order.orderNo}')">
                                            查看评价
                                        </button>
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                        <div class="order-footer">
                            <div class="order-total">
                                <span>实付款：<span class="product-price">¥${order.price.toFixed(2)}</span></span>
                                ${order.expressNo ? `
                                    <span style="margin-left: 20px; color: #666;">
                                        快递单号：${order.expressNo}
                                    </span>
                                ` : ''}
                            </div>
                            <div class="action-buttons" onclick="event.stopPropagation();">
                                ${getActionButtons(order)}
                            </div>
                        </div>
                    </div>
                `;
                orderList.append(orderHtml);
            });
        }

        // 获取状态对应的类名
        function getStatusClass(status) {
            const statusMap = {
                '待付款': 'status-pending',
                '待发货': 'status-shipping',
                '待收货': 'status-shipping',
                '待评价': 'status-completed',
                '已评价': 'status-completed',
                '已取消': 'status-cancelled'
            };
            return statusMap[status] || '';
        }

        // 获取状态文本
        function getStatusText(status) {
            return status || '未知状态';
        }

        // 获取操作按钮
        function getActionButtons(order) {
            let buttons = [];
            
            // 如果是评价相关的状态，使用buyerCommentStatus
            let status = order.buyerCommentStatus || order.status;
            
            switch(status) {
                case '待付款':
                    buttons.push(`<button class="action-btn primary" onclick="payOrder('${order.orderNo}', '${order.price}')">付款</button>`);
                    buttons.push(`<button class="action-btn warning" onclick="showCancelOrderModal('${order.orderNo}')">取消订单</button>`);
                    buttons.push(`<button class="action-btn" onclick="showAddressModal('${order.orderNo}')">修改地址</button>`);
                    break;
                case '待发货':
                    buttons.push(`<button class="action-btn warning" onclick="showCancelOrderModal('${order.orderNo}')">取消订单</button>`);
                    break;
                case '待收货':
                    buttons.push(`<button class="action-btn primary" onclick="confirmReceive('${order.orderNo}')">确认收货</button>`);
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    break;
                case '待评价':
                    buttons.push(`<button class="action-btn primary" onclick="showCommentModal('${order.orderNo}')">评价</button>`);
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    break;
                case '已评价':
                    buttons.push(`<button class="action-btn" onclick="viewComment('${order.orderNo}')">查看评价</button>`);
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    buttons.push(`<button class="action-btn danger" onclick="deleteOrder('${order.orderNo}')">删除订单</button>`);
                    break;
                case '已取消':
                    buttons.push(`<button class="action-btn" onclick="viewCancelReason('${order.orderNo}')">查看取消原因</button>`);
                    buttons.push(`<button class="action-btn danger" onclick="deleteOrder('${order.orderNo}')">删除订单</button>`);
                    break;
            }
            
            return buttons.join('');
        }

        // 取消订单
        function cancelOrder(orderNo, reason) {
            event.stopPropagation();
            if (!reason) {
                alert('请输入取消原因');
                return;
            }
            
            $.ajax({
                url: '/buyer/order/cancel',
                type: 'POST',
                data: { 
                    orderNo: orderNo,
                    reason: reason
                },
                success: function(response) {
                    if (response.state === 1) {
                        alert('取消订单成功');
                        closeModal('cancelOrderModal');
                        loadOrders(); // 刷新订单列表
                    } else {
                        alert(response.msg || '取消订单失败');
                    }
                },
                error: function() {
                    alert('取消订单失败，请稍后重试');
                }
            });
        }

        // 删除订单
        function deleteOrder(orderNo) {
            event.stopPropagation();
            if (!confirm('确定要删除此订单吗？')) {
                return;
            }
            
            $.ajax({
                url: '/buyer/order/delete',
                type: 'POST',
                data: { orderNo: orderNo },
                success: function(response) {
                    if (response.state === 1) {
                        alert('删除订单成功');
                        loadOrders(); // 刷新订单列表
                    } else {
                        alert(response.msg || '删除订单失败');
                    }
                },
                error: function() {
                    alert('删除订单失败，请稍后重试');
                }
            });
        }

        // 显示取消订单模态框
        function showCancelOrderModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            // 重置取消原因输入框
            document.getElementById('cancelReason').value = '';
            showModal('cancelOrderModal');
        }

        // 确认取消订单
        function confirmCancelOrder() {
            const reason = document.getElementById('cancelReason').value.trim();
            if (!reason) {
                alert('请输入取消原因');
                return;
            }
            
            cancelOrder(currentOrderNo, reason);
        }

        // 显示订单详情
        function viewOrderDetail(orderNo) {
            $.ajax({
                url: `/buyer/order/detail/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        console.log("订单详细111", response);
                        const order = response.data;
                        const detailHtml = `
                            <div class="order-detail-section">
                                <h3>基本信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">订单状态：</span>
                                    <span class="detail-value">${getStatusText(order.status)}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">卖家：</span>
                                    <span class="detail-value">
                                        ${order.sellerNickname || '未知卖家'}
                                        <button class="action-btn" onclick="event.stopPropagation(); startChat(${order.sellerId}, '${order.sellerNickname}')">
                                            联系卖家
                                        </button>
                                    </span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">创建时间：</span>
                                    <span class="detail-value">${new Date(order.createTime).toLocaleString()}</span>
                                </div>
                                ${order.paymentTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">支付时间：</span>
                                        <span class="detail-value">${new Date(order.paymentTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                                ${order.deliveryTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">发货时间：</span>
                                        <span class="detail-value">${new Date(order.deliveryTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                                ${order.completionTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">完成时间：</span>
                                        <span class="detail-value">${new Date(order.completionTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                            </div>
                            
                            <div class="order-detail-section">
                                <h3>商品信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">商品名：</span>
                                    <span class="detail-value">${order.productName}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">商品价格：</span>
                                    <span class="detail-value product-price">¥${order.price.toFixed(2)}</span>
                                </div>
                            </div>
                            
                            <div class="order-detail-section">
                                <h3>收货信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">收货人：</span>
                                    <span class="detail-value">${order.recipientName}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">联系电话：</span>
                                    <span class="detail-value">${order.recipientPhone}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">收货地址：</span>
                                    <span class="detail-value">${order.recipientAddress}</span>
                                </div>
                            </div>
                            
                            
                            ${order.expressNo ? `
                                <div class="order-detail-section">
                                    <h3>物流信息</h3>
                                    <div class="detail-row">
                                        <span class="detail-label">快递单号：</span>
                                        <span class="detail-value">${order.expressNo}</span>
                                    </div>
                                    <div class="detail-row">
                                        <span class="detail-label">发货时间：</span>
                                        <span class="detail-value">${new Date(order.deliveryTime).toLocaleString()}</span>
                                    </div>
                                </div>
                            ` : ''}
                            
                            ${order.remark ? `
                                <div class="order-detail-section">
                                    <h3>备注信息</h3>
                                    <div class="detail-row">
                                        <span class="detail-value">${order.remark}</span>
                                    </div>
                                </div>
                            ` : ''}
                        `;
                        
                        $('#orderDetailContent').html(detailHtml);
                        showModal('orderDetailModal');
                    } else {
                        alert('获取订单详情失败');
                    }
                }
            });
        }

        // 显示修改地址模态框
        function showAddressModal(orderNo) {
            event.stopPropagation();
            currentOrderId = orderNo;  // 保存当前订单号
            
            // 获取用户的所有地址
            $.ajax({
                url: '/user/get-addresses',
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const addresses = response.data;
                        renderAddressList(addresses);
                        showModal('addressModal'); // 显示地址选择模态框
                    } else {
                        alert('获取地址列表失败');
                    }
                },
                error: function() {
                    alert('获取地址列表失败');
                }
            });
        }

        // 渲染地址列表
        function renderAddressList(addresses) {
            const addressList = $('.address-list');
            addressList.empty();
            
            addresses.forEach(address => {
                const addressHtml = `
                    <div class="address-item" onclick="selectAddress('${address.id}', this)">
                        <div class="address-name">${address.recipientName}</div>
                        <div class="address-phone">${address.recipientPhone}</div>
                        <div class="address-detail">${address.address}</div>
                    </div>
                `;
                addressList.append(addressHtml);
            });
        }

        // 选择地址
        function selectAddress(addressId, element) {
            // 移除其他地址的选中状态
            $('.address-item').removeClass('selected');
            // 添加当前地址选中状态
            $(element).addClass('selected');
            
            // 更新订单地址
            $.ajax({
                url: '/buyer/order/update-address',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    orderNo: currentOrderId,
                    addressId: addressId
                }),
                success: function(response) {
                    if (response.state === 1) {
                        alert('地址修改成功');
                        closeModal('addressModal');
                        loadOrders();
                    } else {
                        alert(response.msg || '修改失败');
                    }
                },
                error: function() {
                    alert('修改地址失败');
                }
            });
        }

        // 查看取消原因
        function viewCancelReason(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/buyer/order/cancel-reason/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log("取消原因", response);
                    if (response.state === 1) {
                        showCancelReasonModal(response.data.reason);
                        console.log("取消原因", response.data);
                    } else {
                        alert('获取取消原因失败');
                    }
                }
            });
        }

        // 显示取消原因模态框
        function showCancelReasonModal(reason) {
            const modalHtml = `
                <div class="modal-header">
                    <h5 class="modal-title">取消原因</h5>
                    <button type="button" class="close" onclick="closeModal('cancelReasonViewModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <p>${reason || '无取消原因'}</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('cancelReasonViewModal')">关闭</button>
                </div>
            `;
            
            // 如果模态框不存在，创建它
            if (!$('#cancelReasonViewModal').length) {
                $('body').append(`
                    <div class="modal" id="cancelReasonViewModal">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                ${modalHtml}
                            </div>
                        </div>
                    </div>
                `);
            } else {
                $('#cancelReasonViewModal .modal-content').html(modalHtml);
            }
            
            showModal('cancelReasonViewModal');
        }

        // 查看物流
        function viewExpress(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/buyer/order/express/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log("物流信息", response);
                    if (response.state === 1) {
                        const express = response.data;
                        showExpressModal(express);
                    } else {
                        alert('获取物流信息失败');
                    }
                }
            });
        }

        // 显示物流信息模态框
        function showExpressModal(express) {
            const modalHtml = `
                <div class="modal-header">
                    <h5 class="modal-title">物流信息</h5>
                    <button type="button" class="close" onclick="closeModal('expressModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="express-info">
                        <p><strong>快递单号：</strong>${express.express_no}</p>
                        <p><strong>发货时间：</strong>${new Date(express.send_time).toLocaleString()}</p>
                        ${express.company ? `<p><strong>快递公司：</strong>${express.company}</p>` : ''}
                    </div>
                    ${express.traces ? `
                        <div class="logistics-timeline">
                            ${express.traces.map((trace, index) => `
                                <div class="logistics-item ${index === 0 ? 'active' : ''}">
                                    <div class="logistics-time">${new Date(trace.time).toLocaleString()}</div>
                                    <div class="logistics-info">${trace.content}</div>
                                </div>
                            `).join('')}
                        </div>
                    ` : '<p class="text-center text-muted">暂无物流轨迹信息</p>'}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('expressModal')">关闭</button>
                </div>
            `;
            
            // 如果模态框不存在，创建它
            if (!$('#expressModal').length) {
                $('body').append(`
                    <div class="modal" id="expressModal">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                ${modalHtml}
                            </div>
                        </div>
                    </div>
                `);
            } else {
                $('#expressModal .modal-content').html(modalHtml);
            }
            
            showModal('expressModal');
        }

        // 显示模态框
        function showModal(modalId) {
            $(`#${modalId}`).addClass('show').css('display', 'block');
        }

        // 关闭模态框
        function closeModal(modalId) {
            $(`#${modalId}`).removeClass('show').css('display', 'none');
        }

        // 添加物流时间线样式
        const styleSheet = document.createElement('style');
        styleSheet.textContent = `
            .logistics-timeline {
                margin-top: 20px;
                padding: 20px;
                border-left: 2px solid #eee;
            }

            .logistics-item {
                position: relative;
                padding: 0 0 20px 20px;
            }

            .logistics-item:last-child {
                padding-bottom: 0;
            }

            .logistics-item::before {
                content: '';
                position: absolute;
                left: -6px;
                top: 0;
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background: #fff;
                border: 2px solid #ddd;
            }

            .logistics-item.active::before {
                border-color: var(--primary-color);
                background: var(--primary-color);
            }

            .logistics-time {
                font-size: 12px;
                color: #999;
                margin-bottom: 5px;
            }

            .logistics-info {
                color: #333;
                line-height: 1.5;
            }

            .express-info {
                padding: 15px;
                background: #f9f9f9;
                border-radius: 4px;
                margin-bottom: 20px;
            }

            .express-info p {
                margin: 5px 0;
            }

            .modal {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                z-index: 1000;
            }

            .modal.show {
                display: block;
            }

            .modal-dialog {
                margin: 60px auto;
                max-width: 500px;
            }

            .modal-content {
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 3px 15px rgba(0, 0, 0, 0.2);
            }

            .modal-header {
                padding: 15px 20px;
                border-bottom: 1px solid #eee;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .modal-body {
                padding: 20px;
                max-height: 70vh;
                overflow-y: auto;
            }

            .modal-footer {
                padding: 15px 20px;
                border-top: 1px solid #eee;
                text-align: right;
            }

            .close {
                font-size: 24px;
                font-weight: bold;
                color: #666;
                cursor: pointer;
                border: none;
                background: none;
                padding: 0;
            }

            .close:hover {
                color: #333;
            }
        `;
        document.head.appendChild(styleSheet);

        // 支付订单
        function payOrder(orderNo, price) {
            console.log("支付订单：", orderNo, price);
            event.stopPropagation();
            window.open(`https://vdmgkmgxkljg.sealoshzh.site/alipay/pay?traceNo=${orderNo}&totalAmount=${price}&subject=商品购买`, '_blank');
        }

        // 显示空状态
        function showEmptyState(message) {
            $('#orderList').html(`
                <div class="empty-state">
                    <i class="fas fa-box-open"></i>
                    <p>${message}</p>
                </div>
            `);
        }

        // 切换订单状态
        function filterOrders(status) {
            $('.tab').removeClass('active');
            $(event.target).addClass('active');
            
            // 更新URL状态，不刷新页面
            const newUrl = new URL(window.location);
            newUrl.searchParams.set('status', status);
            window.history.pushState({}, '', newUrl);
            
            // 加载对应状态的订单
            loadOrders(status);
        }

        // 查看评价详情
        function viewComment(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/comment/get/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const comment = response.data;
                        document.getElementById('commentModal').style.display = 'block';
                        
                        // 修改模态框标题和内容
                        document.querySelector('#commentModal .modal-header h2').textContent = '评价详情';
                        
                        // 设置评分显示
                        const stars = document.querySelectorAll('#commentModal .star');
                        stars.forEach((star, index) => {
                            if (index < comment.rating) {
                                star.classList.add('active');
                            } else {
                                star.classList.remove('active');
                            }
                            star.style.cursor = 'default';
                            star.style.pointerEvents = 'none';
                        });
                        
                        // 设置评价内容
                        const textarea = document.getElementById('commentContent');
                        textarea.value = comment.content || '暂无评价内容';
                        textarea.readOnly = true;
                        textarea.style.backgroundColor = '#f5f5f5';
                        
                        // 如果有卖家评价，显示卖家评价内容
                        let modalContent = document.querySelector('#commentModal .modal-body');
                        if (comment.sellerContent) {
                            if (!document.getElementById('sellerComment')) {
                                modalContent.insertAdjacentHTML('beforeend', `
                                    <div id="sellerComment" class="seller-comment" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee;">
                                        <h3>卖家评价</h3>
                                        <div class="star-rating seller-rating"></div>
                                        <div class="seller-content" style="margin-top: 10px; padding: 10px; background: #f9f9f9; border-radius: 4px;"></div>
                                    </div>
                                `);
                            }
                            
                            // 设置卖家评分
                            const sellerRating = document.querySelector('.seller-rating');
                            sellerRating.innerHTML = '★'.repeat(comment.sellerRating || 0) + '☆'.repeat(5 - (comment.sellerRating || 0));
                            
                            // 设置卖家评价内容
                            document.querySelector('.seller-content').textContent = comment.sellerContent;
                        }
                        
                        // 隐藏提交按钮，只显示关闭按钮
                        document.querySelector('#commentModal .modal-footer').innerHTML = `
                            <button class="action-btn" onclick="closeCommentModal()">关闭</button>
                        `;
                    } else {
                        alert('获取评价详情失败');
                    }
                }
            });
        }

        // 显示评价模态框（用于新评价）
        function showCommentModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            document.getElementById('commentModal').style.display = 'block';
            
            // 修改模态框标题
            document.querySelector('#commentModal .modal-header h2').textContent = '评价商品';
            
            // 重置评价表单
            const textarea = document.getElementById('commentContent');
            textarea.value = '';
            textarea.readOnly = false;
            textarea.style.backgroundColor = '#fff';
            
            // 重置星级
            const stars = document.querySelectorAll('#commentModal .star');
            stars.forEach(star => {
                star.classList.remove('active');
                star.style.cursor = 'pointer';
                star.style.pointerEvents = 'auto';
            });
            
            // 显示完整的操作按钮
            document.querySelector('#commentModal .modal-footer').innerHTML = `
                <button class="action-btn" onclick="closeCommentModal()">取消</button>
                <button class="action-btn primary" onclick="submitComment()">提交评价</button>
            `;
        }

        // 关闭评价模态框
        function closeCommentModal() {
            document.getElementById('commentModal').style.display = 'none';
        }

        // 显示物流模态框
        function showLogisticsModal(orderNo) {
            event.stopPropagation();
            // 获取物流信息
            fetch(`/api/orders/${orderNo}/logistics`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('expressCompany').textContent = data.expressCompany;
                    document.getElementById('expressNumber').textContent = data.expressNo;
                    
                    // 渲染物流时间线
                    const timeline = document.getElementById('logisticsTimeline');
                    timeline.innerHTML = '';
                    
                    if (data.traces && data.traces.length > 0) {
                        data.traces.forEach((trace, index) => {
                            const item = document.createElement('div');
                            item.className = `logistics-item ${index === 0 ? 'active' : ''}`;
                            item.innerHTML = `
                                <div class="logistics-time">${new Date(trace.time).toLocaleString()}</div>
                                <div class="logistics-info">${trace.content}</div>
                            `;
                            timeline.appendChild(item);
                        });
                    } else {
                        timeline.innerHTML = '<div class="no-data">暂无物流信息</div>';
                    }
                    
                    document.getElementById('logisticsModal').style.display = 'block';
                })
                .catch(error => {
                    console.error('获取物流信息失败:', error);
                    alert('获取物流信息失败，请稍后重试');
                });
        }

        // 关闭物流模态框
        function closeLogisticsModal() {
            document.getElementById('logisticsModal').style.display = 'none';
        }

        // 星级评分处理
        document.querySelectorAll('.star').forEach(star => {
            star.addEventListener('click', function() {
                const rating = this.dataset.rating;
                document.querySelectorAll('.star').forEach(s => {
                    s.classList.toggle('active', s.dataset.rating <= rating);
                });
            });
        });

        // 提交评价
        function submitComment() {
            const content = document.getElementById('commentContent').value.trim();
            const rating = document.querySelectorAll('.star.active').length;
            
            if (!content) {
                alert('请输入评价内容');
                return;
            }
            
            if (rating === 0) {
                alert('请选择评分');
                return;
            }

            const commentData = {
                orderNo: currentOrderNo,
                content: content,
                rating: rating
            };

            // 修改为新的评价提交接口
            $.ajax({
                url: '/comment/buyer/submit',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(commentData),
                success: function(response) {
                    if (response.state === 1) {
                        // 更新卖家信誉分
                        $.ajax({
                            url: '/user/update-credit',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                orderNo: currentOrderNo,
                                rating: rating,
                                type: 'seller' // 表示更新卖家信誉分
                            }),
                            success: function(creditResponse) {
                                if (creditResponse.state === 1) {
                                    console.log('卖家信誉分更新成功');
                                } else {
                                    console.error('卖家信誉分更新失败:', creditResponse.msg);
                                }
                            },
                            error: function(error) {
                                console.error('卖家信誉分更新失败:', error);
                            }
                        });
                        
                        alert('评价成功');
                        closeCommentModal();
                        loadOrders(); // 刷新订单列表
                    } else {
                        alert(response.msg || '评价失败，请重试');
                    }
                },
                error: function(error) {
                    console.error('提交评价失败:', error);
                    alert('评价失败，请稍后重试');
                }
            });
        }

        // 返回上一页
        function goBack() {
            if (document.referrer) {
                window.location.href = document.referrer;
            } else {
                window.history.back();
            }
        }

        // 关闭模态框的其他方式
        window.onclick = function(event) {
            const commentModal = document.getElementById('commentModal');
            const logisticsModal = document.getElementById('logisticsModal');
            if (event.target === commentModal) {
                commentModal.style.display = 'none';
            }
            if (event.target === logisticsModal) {
                logisticsModal.style.display = 'none';
            }
        }

        // 1. startChat函数定义,需添加:
        function startChat(sellerId, productId) {
            event.stopPropagation();
            window.open(`/chat.html?sellerId=${sellerId}&productId=${productId}`, '_blank');
        }

        // 2. showCancelOrderModal函数未定义,需要添加:
        function showCancelOrderModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            showModal('cancelOrderModal');
        }

        // 3. confirmCancelOrder函数未定义,需要添加:
        function confirmCancelOrder() {
            const reason = document.getElementById('cancelReason').value.trim();
            if (!reason) {
                alert('请输入取消原因');
                return;
            }
            
            cancelOrder(currentOrderNo, reason);
            closeModal('cancelOrderModal');
        }
    </script>
</body>
</html> 